import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
  //设置一级路由
  {//主页
    path: '/index',
    name: 'index',
    meta: { title: '主页' },//元信息
    component: () => import('../views/Index.vue'),
    //设置二级路由
    children: [
      {//商品列表
        path: '/index/shoplist',
        name: 'shoplist',
        meta: { title: '主页' },//元信息
        component: () => import('../views/next/Shoplist.vue')
      },
      {//爆爆团
        path: '/index/bao',
        name: 'bao',
        meta: { title: '爆爆团' },//元信息
        component: () => import('../views/next/Bao.vue')
      },
      {//订单
        path: '/index/order',
        name: 'oreder',
        meta: { title: '订单' },//元信息
        component: () => import('../views/next/Order.vue')
      },
      {//我的
        path: '/index/mine',
        name: 'mine',
        meta: { title: '我的' },//元信息
        component: () => import('../views/next/Mine.vue')
      },
      {//设置二级路由重定向
        path: '/index',
        redirect: '/index/shoplist'
      }
    ]
  },
  {//搜索
    path: '/search',
    name: 'search',
    meta: { title: '搜索' },//元信息
    component: () => import('../views/search.vue')
  },
  {//注册
    path: '/register',
    name: 'register',
    meta: { title: '注册' },//元信息
    component: () => import('../views/Register.vue')
  },
  {//登录
    path: '/login',
    name: 'login',
    meta: { title: '登录' },//元信息
    component: () => import('../views/Login.vue')
  },
  {//商品详情
    path: '/detail/:id',
    name: 'detail',
    meta: { title: '商品详情' },//元信息
    component: () => import('../views/details.vue')
  },
  {//收藏的店铺
    path: '/collect',
    name: 'collect',
    meta: { title: '店铺关注' },
    component: () => import('../views/Collect.vue')
  },
  // 跳转我的地址
  {
    path: '/address',
    name: 'address',
    meta: { title: '我的收货地址' },//元信息
    component: () => import('../views/address.vue')
  },
  // 跳转到新增地址
  {
    path: '/newaddress',
    name: 'newaddress',
    meta: { title: '新增地址' },//元信息
    component: () => import('../views/newaddress.vue')
  },
  {
    path: '/amend',
    name: 'amend',
    meta: { title: '修改地址' },//元信息
    component: () => import('../views/amend.vue')
  },

  {//设置一级路由重定向
    path: '/',
    redirect: '/index'
  },
  {//设置404路由
    path: '*',
    name: 'notFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  // 判断本地存储是否有token令牌
  var token = localStorage.getItem('token')
  if (to.path == '/index/order' || to.path == '/index/mine') {
    if (token) {
      next();
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
